﻿#if NETSTANDARD2_0_OR_GREATER || NET5_0_OR_GREATER
using System;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.Json.Serialization;

using zijian666.Abstractions;

namespace zijian666.Json;

/// <summary>
/// 用于处理代理对象的Json转换器工厂
/// </summary>
internal class ProxyObjectJsonConvererFactory : JsonConverterFactory
{
    public override bool CanConvert(Type type)
        => typeof(IObjectReference).IsAssignableFrom(type) || typeof(IObjectProxy).IsAssignableFrom(type);

    public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        => (JsonConverter?)Activator.CreateInstance(typeof(ProxyObjectJsonConverer<>).MakeGenericType(typeToConvert));

    private class ProxyObjectJsonConverer<T> : JsonConverter<T>
    {
        public override bool CanConvert(Type type) => true;

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            var proxy = (value as IObjectProxy)?.GetActualObject() ?? (value as IObjectReference)?.GetRealObject(default) ?? value;
            if (ReferenceEquals(proxy, value))
            {
                JsonSerializer.Serialize(writer, proxy);
            }
            else
            {
                JsonSerializer.Serialize(writer, proxy, options);
            }
        }

        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException();
    }
}

#endif